package com.czb.readcard;

public class ByteUtil {

    /**
     * 将字节数组转换成16进制字符串
     *
     * @param bytes 源字节数组
     * @return 转换后的16进制字符串
     */
    public static String bytes2HexStr(byte... bytes) {
        if (bytes == null || bytes.length == 0) {
            return "";
        }
        return bytes2HexStr(bytes, 0, bytes.length);
    }

    /**
     * 将字节数组转换成16进制字符串
     *
     * @param src    源字节数组
     * @param offset 偏移量
     * @param len    数据长度
     * @return 转换后的16进制字符串
     */
    public static String bytes2HexStr(byte[] src, int offset, int len) {
        int end = offset + len;
        if (src == null || src.length == 0 || offset < 0 || len < 0 || end > src.length) {
            return "";
        }
        byte[] buffer = new byte[len * 2];
        int h = 0, l = 0;
        for (int i = offset, j = 0; i < end; i++) {
            h = src[i] >> 4 & 0x0f;
            l = src[i] & 0x0f;
            buffer[j++] = (byte) (h > 9 ? h - 10 + 'A' : h + '0');
            buffer[j++] = (byte) (l > 9 ? l - 10 + 'A' : l + '0');
        }
        return new String(buffer);
    }

    public static byte[] hexStr2Bytes(String hexStr) {
        hexStr = hexStr.toLowerCase();
        int length = hexStr.length();
        byte[] bytes = new byte[length >> 1];
        int index = 0;
        for (int i = 0; i < length; i++) {
            if (index > hexStr.length() - 1) return bytes;
            byte highDit = (byte) (Character.digit(hexStr.charAt(index), 16) & 0xFF);
            byte lowDit = (byte) (Character.digit(hexStr.charAt(index + 1), 16) & 0xFF);
            bytes[i] = (byte) (highDit << 4 | lowDit);
            index += 2;
        }
        return bytes;
    }
}
